import '../models/practice_record.dart';
import '../services/database_service.dart';

class PracticeRecordRepository {
  final DatabaseService _dbService = DatabaseService();
  static const String _tableName = DatabaseService.practiceRecordsTable;

  /// 添加练习记录
  Future<int> addPracticeRecord(PracticeRecord record) async {
    final data = record.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有练习记录
  Future<List<PracticeRecord>> getAllPracticeRecords() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => PracticeRecord.fromMap(data)).toList();
  }

  /// 根据ID获取练习记录
  Future<PracticeRecord?> getPracticeRecordById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? PracticeRecord.fromMap(result) : null;
  }

  /// 根据题目ID获取练习记录
  Future<List<PracticeRecord>> getPracticeRecordsByQuestionId(int questionId) async {
    final results = await _dbService.getByField(_tableName, 'questionId', questionId);
    return results.map((data) => PracticeRecord.fromMap(data)).toList();
  }

  /// 获取最近的练习记录
  Future<List<PracticeRecord>> getRecentPracticeRecords(int count) async {
    final allRecords = await getAllPracticeRecords();
    allRecords.sort((a, b) => b.createdAt.compareTo(a.createdAt));
    return allRecords.take(count).toList();
  }

  /// 获取指定日期范围的练习记录
  Future<List<PracticeRecord>> getPracticeRecordsByDateRange(
    DateTime startDate,
    DateTime endDate,
  ) async {
    final allRecords = await getAllPracticeRecords();
    final startTimestamp = startDate.millisecondsSinceEpoch;
    final endTimestamp = endDate.millisecondsSinceEpoch;
    
    return allRecords.where((record) => 
      record.createdAt >= startTimestamp && record.createdAt <= endTimestamp
    ).toList();
  }

  /// 获取今日练习记录
  Future<List<PracticeRecord>> getTodayPracticeRecords() async {
    final now = DateTime.now();
    final startOfDay = DateTime(now.year, now.month, now.day);
    final endOfDay = DateTime(now.year, now.month, now.day, 23, 59, 59);
    
    return await getPracticeRecordsByDateRange(startOfDay, endOfDay);
  }

  /// 获取本周练习记录
  Future<List<PracticeRecord>> getThisWeekPracticeRecords() async {
    final now = DateTime.now();
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));
    final startOfWeekDay = DateTime(startOfWeek.year, startOfWeek.month, startOfWeek.day);
    
    return await getPracticeRecordsByDateRange(startOfWeekDay, now);
  }

  /// 获取本月练习记录
  Future<List<PracticeRecord>> getThisMonthPracticeRecords() async {
    final now = DateTime.now();
    final startOfMonth = DateTime(now.year, now.month, 1);
    
    return await getPracticeRecordsByDateRange(startOfMonth, now);
  }

  /// 获取正确答题记录
  Future<List<PracticeRecord>> getCorrectPracticeRecords() async {
    final allRecords = await getAllPracticeRecords();
    return allRecords.where((record) => record.isCorrect).toList();
  }

  /// 获取错误答题记录
  Future<List<PracticeRecord>> getIncorrectPracticeRecords() async {
    final allRecords = await getAllPracticeRecords();
    return allRecords.where((record) => !record.isCorrect).toList();
  }

  /// 更新练习记录
  Future<void> updatePracticeRecord(PracticeRecord record) async {
    await _dbService.update(_tableName, record.toMap());
  }

  /// 删除练习记录
  Future<void> deletePracticeRecord(int id) async {
    await _dbService.delete(_tableName, id);
  }

  /// 批量添加练习记录
  Future<List<int>> addPracticeRecords(List<PracticeRecord> records) async {
    final List<int> ids = [];
    for (final record in records) {
      final id = await addPracticeRecord(record);
      ids.add(id);
    }
    return ids;
  }

  /// 获取练习记录总数
  Future<int> getPracticeRecordCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取练习统计
  Future<Map<String, dynamic>> getPracticeStats() async {
    final allRecords = await getAllPracticeRecords();
    final totalCount = allRecords.length;
    final correctCount = allRecords.where((record) => record.isCorrect).length;
    final incorrectCount = totalCount - correctCount;
    final accuracy = totalCount > 0 ? (correctCount / totalCount * 100) : 0.0;
    
    final totalTime = allRecords.fold<int>(0, (sum, record) => sum + record.timeSpent);
    final averageTime = totalCount > 0 ? (totalTime / totalCount) : 0.0;
    
    return {
      'totalCount': totalCount,
      'correctCount': correctCount,
      'incorrectCount': incorrectCount,
      'accuracy': accuracy,
      'totalTime': totalTime,
      'averageTime': averageTime,
    };
  }

  /// 获取今日练习统计
  Future<Map<String, dynamic>> getTodayPracticeStats() async {
    final todayRecords = await getTodayPracticeRecords();
    final totalCount = todayRecords.length;
    final correctCount = todayRecords.where((record) => record.isCorrect).length;
    final incorrectCount = totalCount - correctCount;
    final accuracy = totalCount > 0 ? (correctCount / totalCount * 100) : 0.0;
    
    final totalTime = todayRecords.fold<int>(0, (sum, record) => sum + record.timeSpent);
    
    return {
      'totalCount': totalCount,
      'correctCount': correctCount,
      'incorrectCount': incorrectCount,
      'accuracy': accuracy,
      'totalTime': totalTime,
    };
  }

  /// 获取按日期分组的练习统计
  Future<Map<String, Map<String, dynamic>>> getDailyPracticeStats(int days) async {
    final endDate = DateTime.now();
    final startDate = endDate.subtract(Duration(days: days - 1));
    final records = await getPracticeRecordsByDateRange(startDate, endDate);
    
    final dailyStats = <String, Map<String, dynamic>>{};
    
    for (int i = 0; i < days; i++) {
      final date = startDate.add(Duration(days: i));
      final dateKey = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      
      final dayStart = DateTime(date.year, date.month, date.day);
      final dayEnd = DateTime(date.year, date.month, date.day, 23, 59, 59);
      
      final dayRecords = records.where((record) => 
        record.createdAt >= dayStart.millisecondsSinceEpoch &&
        record.createdAt <= dayEnd.millisecondsSinceEpoch
      ).toList();
      
      final totalCount = dayRecords.length;
      final correctCount = dayRecords.where((record) => record.isCorrect).length;
      final accuracy = totalCount > 0 ? (correctCount / totalCount * 100) : 0.0;
      
      dailyStats[dateKey] = {
        'totalCount': totalCount,
        'correctCount': correctCount,
        'incorrectCount': totalCount - correctCount,
        'accuracy': accuracy,
      };
    }
    
    return dailyStats;
  }

  /// 清空所有练习记录
  Future<void> clearAllPracticeRecords() async {
    await _dbService.clearTable(_tableName);
  }

  /// 删除指定日期之前的练习记录
  Future<void> deletePracticeRecordsBefore(DateTime date) async {
    final allRecords = await getAllPracticeRecords();
    final timestamp = date.millisecondsSinceEpoch;
    
    for (final record in allRecords) {
      if (record.createdAt < timestamp && record.id != null) {
        await deletePracticeRecord(record.id!);
      }
    }
  }
}